<template>
  <div id="particlesId" class="login-content" :style="'--color:' + variables">
    <div class="login-form-content">
      <div class="login-form-title">
        <h2>{{ title }}</h2>
      </div>
      <div class="login-form">
        <el-form
          ref="loginForm"
          style="width: 100%;"
          :model="loginForm"
          :rules="loginRules"
          :show-message="showMessage"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <el-input v-model.trim="loginForm.username" size="small" placeholder="请输入登录账号" type="text" autocomplete="off">
              <svg-icon slot="prefix" class="el-icon-user" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              :type="passwordType"
              size="small"
              placeholder="请输入登录密码"
              name="password"
              show-password
              autocomplete="off"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" class="el-icon-lock" />
            </el-input>
          </el-form-item>
          <div style="height: 20px;margin-bottom: 10px;">
            账号：visitor 密码：visitor
          </div>
          <div class="form-submit">
            <el-popover
              ref="refPopover"
              v-model="showPopover"
              :open-delay="500"
              placement="top"
              width="350"
              trigger="manual"
            >
              <captcha ref="refCaptcha" @ok="okCaptcha" @close="closeCaptcha" @refresh="$refs.refPopover.updatePopper()" />
              <el-button
                slot="reference"
                v-throttle
                size="small"
                style="width: 100%;"
                :loading="loading"
                type="primary"
                @click.native.prevent.stop="handleLogin"
              >登录</el-button>
            </el-popover>
          </div>
        </el-form>
      </div>
    </div>
    <div class="copyright">
      <p>Copyright © 2023-2026 easyboot.cn 版权所有.</p>
      <span>
        <img src="@/assets/emblem.png" alt="">
        <a href="https://beian.mps.gov.cn/#/query/webSearch?code=44030002001475" rel="noreferrer" target="_blank">粤公网安备44030002001475</a>
        <el-link
          class="copyright-link"
          :underline="false"
          href="https://beian.miit.gov.cn/"
          type="primary"
          target="_blank"
        >粤ICP备2023127161号</el-link>
      </span>
    </div>
  </div>
</template>
<script>
import particles from '@/utils/particles.js'
import particlesConfig from './particles.json'
import { validUsername, validPassword } from '@/utils/validate'
import Captcha from '@/components/Captcha'
export default {
  components: { Captcha },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录账号'))
      } if (value.length < 5 || value.length > 15) {
        callback(new Error('账号长度在5-15位之间'))
      } else if (!validUsername(value)) {
        callback(new Error('账号格式不正确，仅支持字母、数字和下划线'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录密码'))
      } if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度在6-20位之间'))
      } else if (!validPassword(value)) {
        callback(new Error('密码格式不正确，仅支持字母、数字和下划线'))
      } else {
        callback()
      }
    }
    return {
      passwordType: 'password',
      enableValidate: true,
      loading: false,
      showPopover: false, // 是否显示验证码组件
      showMessage: false,
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
        password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
      },
      codeForm: {
        id: ''
      }
    }
  },
  computed: {
    variables() {
      return localStorage.getItem('theme') || this.$store.state.settings.theme
    },
    // 标题
    title() {
      return this.$store.state.settings.title + '后台登录'
    }
  },
  mounted() {
    particles.particlesJS('particlesId', particlesConfig)
  },
  beforeDestroy() {
    if (particles.pJSDom && particles.pJSDom.length > 0) {
      particles.pJSDom.forEach(pJSDomItem => {
        pJSDomItem.pJS.fn.vendors.destroypJS()
      })
    }
  },
  methods: {
    // 表单校验
    handleLogin() {
      this.$refs.loginForm.validate((valid, obj) => {
        if (valid) {
          if (!this.enableValidate) {
            this.login()
            return
          }
          if (!this.showPopover) {
            this.showCaptcha()
          }
        } else {
          const field = []
          for (const key in obj) {
            field.push(obj[key][0].message)
          }
          this.$message({ message: field[0], type: 'error' })
          return false
        }
      })
    },
    // 登录
    login() {
      this.loading = true
      this.$store.dispatch('user/login', this.loginForm).then((res) => {
        this.$router.push({
          path: '/'
        })
      }).finally(() => {
        this.loading = false
      })
    },
    // 显示验证码组件
    showCaptcha() {
      this.showPopover = true
      this.$refs.refCaptcha.getCode()
    },
    // 验证码验证通过
    okCaptcha(id) {
      this.loginForm.id = id
      this.closeCaptcha()
      this.login()
    },
    // 关闭验证码组件
    closeCaptcha() {
      this.showPopover = false
    }
  }
}
</script>
<style scoped lang="scss">
.login-content {
  width: 100%;
  height: 100%;
  background-color: var(--color);
  box-sizing: border-box;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  position: relative;
  overflow: hidden;
}

.login-form-content {
  width: 350px;
  height: 290px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  position: absolute;
  top: calc(50% - 120px);
  left: calc(50% - 175px);
  animation: big .6s;
}

@keyframes big {
  from {
    transform: scale(0.1);
  }
  to {
    transform: scale(1);
  }
}

.login-form-title {
  color: var(--color);
}

.login-form {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 0px 30px 30px 30px;
}

.copyright {
  width: 100%;
  position: absolute;
  bottom: 15px;
  font-size: 13px;
  color: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  span {
    display: inline-block;
    display: flex;
    align-items: center;
  }
  .copyright-link {
    color: #fff;
    font-size: 13.3px;
  }
  .copyright-link:hover, a:hover {
    color: #109595;
  }
  img {
    width: 15px;
    height: 15px;
  }
  a {
    text-decoration: none;
    margin-left: 8px;
    margin-right: 12px;
  }
}
</style>
